package com.eunion.core;

import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * 日志工具类.
 * 
 * 
 * @version 2015年8月24日
 */
public final class LogUtil {

    /** UID .*/
    public static final String UID = "UID";

    /** START. */
    public static final String START = "START";
//
//    /** EEND .*/
//    public static final String EN = "EEND";

    private LogUtil() {
    }

    /**
     * 以当前类命名的logger.
     */
    public static Logger get(Class<?> clazz) {
        return LoggerFactory.getLogger(clazz.getSimpleName());
    }

    /**
     * 获取所有MDC,日志.如果没有返回null.
     */
    public static String getAllMdc() {
        Map<String, String> all = MDC.getCopyOfContextMap();
        if (all == null || all.isEmpty()) {
            return null;
        } else {
            // Rule Replace the synchronized class "StringBuffer" by an unsynchronized one such as
            // "StringBuilder".
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> entry : all.entrySet()) {
                sb.append(entry.getKey());
                sb.append(":");
                sb.append(entry.getValue());
                sb.append(" ");
            }
            return "[".concat(sb.toString()).concat("]");
        }
    }

    /**
     * 设置UID.
     */
    public static void setMDCUUID() {
        MDC.put(UID, random6());
    }

    /**
     * 设置key,value.
     */
    public static void setMDC(String key, String value) {
        MDC.put(key, value);
    }

    /**
     * 清理MDC.
     */
    public static void clearMDC() {
        MDC.clear();
    }

    /**
     * 生成6位随机数.
     */
    public static String random6() {
        Random random = new Random();
        int x = random.nextInt(899999) + 100000;
        return String.valueOf(x);
    }

}
